package com.quanyan.orderpay.component;

import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.common.utils.SerializeUtils;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Zheng.Ke
 * Date 2016/11/3.
 */
@Component
public class OrderPayRedisTemplate extends RedisTemplate {
    private static final Logger logger = LoggerFactory.getLogger(OrderPayRedisTemplate.class);

    public void set(String key, String value) {
        jedisCluster.set(getByte(key), getByte(value));
    }

    public void setex(String key, String value, int seconds) {
        if (seconds < 0) {
            seconds = 0;
        }
        jedisCluster.setex(getByte(key), seconds, getByte(value));
    }

    public String get(String key) {
        byte[] resultByte = null;
        try {
            resultByte = jedisCluster.get(getByte(key));
        } catch (Exception e) {
            logger.error(ObjectUtil.getFullStackTraceToString(e));
        }
        if (null != resultByte){
            return new String(resultByte);
        } else {
            return null;
        }
    }

    public String hget(String key, String field) {
        byte[] resultByte = null;
        try {
            resultByte = jedisCluster.hget(getByte(key), getByte(field));
        } catch (Exception e) {
            logger.error(ObjectUtil.getFullStackTraceToString(e));
        }
        if (null != resultByte){
            return new String(resultByte);
        } else {
            return null;
        }
    }



    public void hmset(String key, Map<String, String> map) {
        hmset(key, map, null);
    }

    public void hmset(String key, Map<String, String> map, Integer expireSeconds) {
        try {
            Map<byte[],byte[]> mapByte=new HashMap<byte[],byte[]>();
            Iterator<Map.Entry<String,String>> entries = map.entrySet().iterator();

            while (entries.hasNext()) {

                Map.Entry<String, String> entry = entries.next();
                mapByte.put(entry.getKey().getBytes(),entry.getValue().getBytes());
            }
            jedisCluster.hmset(key.getBytes(), mapByte);
            if (expireSeconds != null && expireSeconds >= 0) {
                jedisCluster.expire(key.getBytes(), expireSeconds);
            }
        } catch (Exception e) {
            logger.error(ObjectUtil.getFullStackTraceToString(e));
        }
    }

    private byte[] getByte(Object key) {
        if (key instanceof String) {
            return String.valueOf(key).getBytes();
        } else {
            return SerializeUtils.serialize(key);
        }
    }

}
